<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' data: https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' data: https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net; connect-src 'self'; img-src 'self' data: https:;">
    <title>管理后台 - 百日行动线索收集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="css/admin-mobile.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            width: 250px;
            z-index: 1000;
            transform: translateX(-100%);
            transition: transform 0.3s ease;
        }
        .sidebar.show {
            transform: translateX(0);
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 10px;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .main-content {
            margin-left: 0;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }
        .mobile-header {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 15px 20px;
            display: none;
        }
        .mobile-menu-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: #333;
        }
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .sidebar-overlay.show {
            opacity: 1;
            visibility: visible;
        }
        .navbar {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: transform 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
        }
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .recent-clues {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .clue-item {
            border-left: 4px solid #667eea;
            padding: 15px;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 0 8px 8px 0;
        }
        .status-badge {
            font-size: 12px;
            padding: 4px 8px;
            border-radius: 20px;
        }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-processing { background: #d1ecf1; color: #0c5460; }
        .status-completed { background: #d4edda; color: #155724; }
        .status-closed { background: #f8d7da; color: #721c24; }
        
        /* 桌面端样式 */
        @media (min-width: 992px) {
            .sidebar {
                transform: translateX(0);
            }
            .main-content {
                margin-left: 250px;
            }
            .mobile-header {
                display: none !important;
            }
        }
        
        /* 移动端样式 */
        @media (max-width: 991.98px) {
            .mobile-header {
                display: flex !important;
                justify-content: space-between;
                align-items: center;
            }
            .navbar {
                display: none;
            }
            .stat-card {
                margin-bottom: 15px;
            }
            .chart-container {
                padding: 15px;
            }
            .recent-clues {
                padding: 15px;
            }
            .stat-icon {
                width: 50px;
                height: 50px;
                font-size: 20px;
            }
            .stat-card h3 {
                font-size: 1.5rem;
            }
            .main-content {
                padding: 10px;
            }
        }
        
        /* 超小屏幕适配 */
        @media (max-width: 576px) {
            .col-md-3 {
                margin-bottom: 15px;
            }
            .chart-container {
                padding: 10px;
            }
            .chart-container h5 {
                font-size: 1rem;
                margin-bottom: 15px;
            }
            .recent-clues {
                padding: 10px;
            }
            .clue-item {
                padding: 10px;
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <!-- 移动端头部 -->
    <div class="mobile-header">
        <button class="mobile-menu-btn" id="mobileMenuBtn">
            <i class="bi bi-list"></i>
        </button>
        <h5 class="mb-0">管理后台</h5>
        <div class="dropdown">
            <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                <i class="bi bi-person-circle"></i>
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item" href="#" id="mobileLogoutBtn"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
            </ul>
        </div>
    </div>
    
    <!-- 侧边栏遮罩层 -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- 侧边栏 -->
    <nav class="sidebar" id="sidebar">
        <div class="p-3">
            <h5 class="text-white mb-4">
                <i class="bi bi-shield-check me-2"></i>
                管理后台
            </h5>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link active" href="#" data-page="dashboard">
                        <i class="bi bi-speedometer2 me-2"></i>仪表板
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-page="clues">
                        <i class="bi bi-file-text me-2"></i>线索管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-page="statistics">
                        <i class="bi bi-bar-chart me-2"></i>统计分析
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-page="users">
                        <i class="bi bi-people me-2"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-page="settings">
                        <i class="bi bi-gear me-2"></i>系统设置
                    </a>
                </li>
            </ul>
        </div>
        <div class="mt-auto p-3">
            <button class="btn btn-outline-light btn-sm w-100" id="sidebarLogoutBtn">
                <i class="bi bi-box-arrow-right me-2"></i>退出登录
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand-lg navbar-light">
            <div class="container-fluid">
                <h4 class="mb-0">仪表板</h4>
                <div class="navbar-nav ms-auto">
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-2"></i>
                            <span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" id="navLogoutBtn"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                            <i class="bi bi-file-text"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="totalClues">0</h3>
                            <p class="text-muted mb-0">总线索数</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);">
                            <i class="bi bi-clock"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="pendingClues">0</h3>
                            <p class="text-muted mb-0">待处理</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);">
                            <i class="bi bi-arrow-repeat"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="processingClues">0</h3>
                            <p class="text-muted mb-0">处理中</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%);">
                            <i class="bi bi-check-circle"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="completedClues">0</h3>
                            <p class="text-muted mb-0">已完成</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="chart-container">
                    <h5 class="mb-3">处理状态分布</h5>
                    <div style="height: 200px; position: relative;">
                        <canvas id="statusChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <h5 class="mb-3">案件类型分布</h5>
                    <div style="height: 200px; position: relative;">
                        <canvas id="categoryChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-md-12">
                <div class="chart-container">
                    <h5 class="mb-3">乡镇街道统计</h5>
                    <div style="height: 300px; position: relative;">
                        <canvas id="townshipChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近线索 -->
        <div class="recent-clues">
            <h5 class="mb-3">最近线索</h5>
            <div id="recentCluesList">
                <!-- 动态加载 -->
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let statusChart, categoryChart, townshipChart;
        
        // 移动端侧边栏控制
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.querySelector('.sidebar-overlay');
            
            if (sidebar.classList.contains('show')) {
                sidebar.classList.remove('show');
                overlay.classList.remove('show');
                document.body.style.overflow = '';
            } else {
                sidebar.classList.add('show');
                overlay.classList.add('show');
                document.body.style.overflow = 'hidden';
            }
        }
        
        // 检测窗口大小变化
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 992) {
                // 桌面端：隐藏移动端菜单
                const sidebar = document.getElementById('sidebar');
                const overlay = document.querySelector('.sidebar-overlay');
                sidebar.classList.remove('show');
                overlay.classList.remove('show');
                document.body.style.overflow = '';
            }
        });
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadDashboardData();
            initCharts();
            bindEventListeners();
        });

        // 检查认证状态
        function checkAuth() {
            const token = localStorage.getItem('adminToken');
            if (!token) {
                window.location.href = '/admin/login.html';
                return;
            }
            
            const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
            document.getElementById('adminName').textContent = adminUser.real_name || '管理员';
        }

        // 加载仪表板数据
        async function loadDashboardData() {
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch('/api/admin/statistics/overview', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const data = result.data;
                    
                    // 更新统计卡片
                    document.getElementById('totalClues').textContent = data.total_clues || 0;
                    document.getElementById('pendingClues').textContent = data.pending_clues || 0;
                    document.getElementById('processingClues').textContent = data.processing_clues || 0;
                    document.getElementById('completedClues').textContent = data.completed_clues || 0;
                    
                    // 更新图表
                    updateStatusChart(data);
                    updateCategoryChart(data.category_stats || []);
                    updateTownshipChart(data.township_stats || []);
                    
                    // 加载最近线索
                    loadRecentClues();
                } else {
                    console.error('加载数据失败');
                }
            } catch (error) {
                console.error('加载数据错误:', error);
            }
        }

        // 初始化图表
        function initCharts() {
            // 状态分布饼图
            const statusCtx = document.getElementById('statusChart').getContext('2d');
            statusChart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['待处理', '处理中', '已完成', '已关闭'],
                    datasets: [{
                        data: [0, 0, 0, 0],
                        backgroundColor: ['#ffc107', '#17a2b8', '#28a745', '#dc3545'],
                        borderWidth: 0,
                        cutout: '60%'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        }
                    },
                    layout: {
                        padding: {
                            top: 10,
                            bottom: 10
                        }
                    }
                }
            });

            // 类型分布饼图
            const categoryCtx = document.getElementById('categoryChart').getContext('2d');
            categoryChart = new Chart(categoryCtx, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: ['#667eea', '#764ba2', '#f093fb', '#f5576c'],
                        borderWidth: 0,
                        cutout: '60%'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        }
                    },
                    layout: {
                        padding: {
                            top: 10,
                            bottom: 10
                        }
                    }
                }
            });

            // 乡镇统计柱状图
            const townshipCtx = document.getElementById('townshipChart').getContext('2d');
            townshipChart = new Chart(townshipCtx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: '线索数量',
                        data: [],
                        backgroundColor: 'rgba(102, 126, 234, 0.8)',
                        borderColor: 'rgba(102, 126, 234, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }

        // 更新状态图表
        function updateStatusChart(data) {
            statusChart.data.datasets[0].data = [
                data.pending_clues || 0,
                data.processing_clues || 0,
                data.completed_clues || 0,
                data.closed_clues || 0
            ];
            statusChart.update();
        }

        // 更新类型图表
        function updateCategoryChart(categoryStats) {
            const labels = categoryStats.map(item => item.category);
            const data = categoryStats.map(item => item.count);
            
            categoryChart.data.labels = labels;
            categoryChart.data.datasets[0].data = data;
            categoryChart.update();
        }

        // 更新乡镇图表
        function updateTownshipChart(townshipStats) {
            const labels = townshipStats.map(item => item.township_name || item.region || item.district);
            const data = townshipStats.map(item => item.count);
            
            townshipChart.data.labels = labels;
            townshipChart.data.datasets[0].data = data;
            townshipChart.update();
        }

        // 绑定事件监听器
        function bindEventListeners() {
            // 退出登录按钮
            const logoutButtons = [
                document.getElementById('mobileLogoutBtn'),
                document.getElementById('sidebarLogoutBtn'),
                document.getElementById('navLogoutBtn')
            ];
            
            logoutButtons.forEach(btn => {
                if (btn) {
                    btn.addEventListener('click', function(e) {
                        e.preventDefault();
                        logout();
                    });
                }
            });
            
            // 移动端菜单按钮
            const mobileMenuBtn = document.getElementById('mobileMenuBtn');
            if (mobileMenuBtn) {
                mobileMenuBtn.addEventListener('click', toggleSidebar);
            }
            
            // 侧边栏遮罩层
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            if (sidebarOverlay) {
                sidebarOverlay.addEventListener('click', toggleSidebar);
            }
            
            // 导航菜单点击事件
            document.querySelectorAll('.sidebar .nav-link').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const page = this.dataset.page;
                    
                    // 移动端：点击菜单项后关闭侧边栏
                    if (window.innerWidth < 992) {
                        toggleSidebar();
                    }
                    
                    // 更新活动状态
                    document.querySelectorAll('.sidebar .nav-link').forEach(l => l.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 根据页面跳转
                    switch(page) {
                        case 'dashboard':
                            // 当前页面，刷新数据
                            loadDashboardData();
                            break;
                        case 'clues':
                            window.location.href = '/admin/clues.html';
                            break;
                        case 'statistics':
                            window.location.href = '/admin/statistics.html';
                            break;
                        case 'users':
                            window.location.href = '/admin/users.html';
                            break;
                        case 'settings':
                            window.location.href = '/admin/settings.html';
                            break;
                    }
                });
            });
        }

        // 加载最近线索
        async function loadRecentClues() {
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch('/api/admin/clues?page=1&page_size=5', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const clues = result.data.list || [];
                    
                    const container = document.getElementById('recentCluesList');
                    container.innerHTML = clues.map(clue => `
                        <div class="clue-item">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h6 class="mb-1">${clue.title || '线索标题'}</h6>
                                    <p class="mb-1 text-muted">${clue.category} - ${clue.clue_no}</p>
                                    <small class="text-muted">${formatDate(clue.created_at)}</small>
                                    ${clue.reporter_phone ? `<small class="text-info d-block">联系电话: ${clue.reporter_phone}</small>` : ''}
                                </div>
                                <div>
                                    <span class="status-badge status-${clue.status}">${getStatusText(clue.status)}</span>
                                    <button class="btn btn-sm btn-outline-primary ms-2 view-clue-btn" data-clue-id="${clue.id}">
                                        查看
                                    </button>
                                </div>
                            </div>
                        </div>
                    `).join('');
                    
                    // 为查看按钮绑定事件
                    bindViewClueButtons();
                } else {
                    document.getElementById('recentCluesList').innerHTML = '<div class="text-center text-muted">暂无线索数据</div>';
                }
            } catch (error) {
                console.error('加载最近线索错误:', error);
                document.getElementById('recentCluesList').innerHTML = '<div class="text-center text-danger">加载失败</div>';
            }
        }

        // 绑定查看线索按钮事件
        function bindViewClueButtons() {
            const viewButtons = document.querySelectorAll('.view-clue-btn');
            viewButtons.forEach(btn => {
                btn.addEventListener('click', function() {
                    const clueId = this.dataset.clueId;
                    viewClue(clueId);
                });
            });
        }

        // 退出登录
        async function logout() {
            try {
                const token = localStorage.getItem('adminToken');
                
                // 如果有token，先调用后端退出接口
                if (token) {
                    try {
                        const response = await fetch('/api/admin/logout', {
                            method: 'POST',
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const result = await response.json();
                        console.log('退出登录响应:', result);
                    } catch (error) {
                        console.error('调用退出接口失败:', error);
                        // 即使接口调用失败，也继续清除本地数据
                    }
                }
                
                // 清除本地存储
                localStorage.removeItem('adminToken');
                localStorage.removeItem('adminUser');
                
                // 跳转到登录页面
                window.location.href = '/admin/login.html';
                
            } catch (error) {
                console.error('退出登录失败:', error);
                
                // 即使出错也清除本地数据并跳转
                localStorage.removeItem('adminToken');
                localStorage.removeItem('adminUser');
                window.location.href = '/admin/login.html';
            }
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'pending': '待处理',
                'processing': '处理中',
                'completed': '已完成',
                'closed': '已关闭'
            };
            return statusMap[status] || status;
        }

        // 查看线索详情
        function viewClue(clueId) {
            window.location.href = `/admin/clues.html?id=${clueId}`;
        }
    </script>
</body>
</html> 